package club.pinea.session;

import club.pinea.interfaces.MessageCallback;
import club.pinea.proto.BasicProto;
import club.pinea.util.ProtoCommandMap;
import com.google.protobuf.Message;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息发送
 */
public class MessageSend {
    static Logger log = LoggerFactory.getLogger(MessageSend.class);

    public static boolean sendToUser(Message msg, ChannelHandlerContext context) {
        return sendToUser(msg, context, null);
    }

    public static boolean sendToUser(Message msg, ChannelHandlerContext context, MessageCallback callback) {
        if (context == null) {
            log.error("******** sendToServer.session null");
            return false;
        }
        if (msg == null) {
            log.error("******** sendToServer.msg null");
            return false;
        }
        try {
            Integer head = ProtoCommandMap.getCommand(msg.getDescriptorForType().getName());
            if (head != null) {
                BasicProto.BaseMessage.Builder im = BasicProto.BaseMessage.newBuilder();
                im.setOrder(head);
                im.setBody(msg.toByteString());
                context.writeAndFlush(im.build());
                log.debug("发送消息【" + Integer.toHexString(head) + "】到服务端，大小：【" + im.build().getSerializedSize() + "】,消息体：" + msg.toString());
                if (callback != null) {
                    CallbackContainer.putCallback(ProtoCommandMap.getCommand(msg.getDescriptorForType().getName()), callback);
                }
                return true;
            } else {
                log.error("发送服务端有误::" + msg.getDescriptorForType().getName());
            }
        } catch (Exception e) {
            log.error("发送请求消息失败。", e);
        }
        return false;
    }
}
